package aliyun.cx.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aliyun.cx.admin.entity.Tag;
import aliyun.cx.admin.mapper.TagMapper;
import aliyun.cx.admin.service.TagService;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    
    private final TagMapper tagMapper;
    
    public TagServiceImpl(TagMapper tagMapper) {
        this.tagMapper = tagMapper;
    }
    
    @Override
    public Page<Tag> getTagPage(Integer current, Integer size, String name) {
        Page<Tag> page = new Page<>(current, size);
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        
        // 如果提供了搜索名称，添加模糊查询条件
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name.trim());
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        return page(page, queryWrapper);
    }
    
    @Override
    public List<Tag> getAllTags() {
        return list();
    }
    
    @Override
    public boolean createTag(Tag tag) {
        tag.setCreateTime(LocalDateTime.now());
        return save(tag);
    }
    
    @Override
    public boolean updateTag(Tag tag) {
        return updateById(tag);
    }
    
    @Override
    public boolean deleteTag(Long id) {
        // 软删除：将deleted字段设置为1
        Tag tag = new Tag();
        tag.setId(id);
        tag.setDeleted(1);
        return updateById(tag);
    }
    
    @Override
    public boolean isNameExists(String name, Long excludeId) {
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return count(queryWrapper) > 0;
    }
    
    @Override
    public boolean isTagInUse(Long id) {
        // 检查是否有文章使用该标签
        return tagMapper.countArticlesByTagId(id) > 0;
    }
    
    @Override
    public boolean restoreTag(Long id) {
        // 恢复：将deleted字段设置为0
        Tag tag = new Tag();
        tag.setId(id);
        tag.setDeleted(0);
        return updateById(tag);
    }
}
